<?php
/**
 * 
 * Smarty plugin
 * 
 * $Id: modifier.supertruncate.php 121 2010-05-28 07:57:29Z Administrator $
 * $Revision: 121 $
 * $Author: Administrator $
 * $Date: 2010-05-28 15:57:29 +0800 (星期五, 28 五月 2010) $
 * @package fastlib
 * @subpackage smarty
 */
/**
 * Smarty supertruncate modifier plugin
 *
 * Type:	modifier<br />
 * Name:	supertruncate<br />
 * 
 * 截取中文字符串
 *
 * @param string $string 要截取的字符
 * @param int $length 截取长度
 * @param string $etc 省略号
 * @param bool $middle 是否省略在中间的字符
 * @return string 截取后的字符串
 */
function smarty_modifier_supertruncate($string, $length = 80, $etc = '...', $middle = false) {
	global $flibcfg;
	$charset = $flibcfg ['charset'];
	if (extension_loaded ( 'mbstring' )) {
		$strlen = mb_strlen ( $string, $charset );
		if ($strlen > $length) {
			$length -= min ( $length, strlen ( $etc ) );
			if (! $middle) {
				$string = mb_substr ( $string, 0, floor ( $length ), $charset ) . $etc;
			} else {
				$string = mb_substr ( $string, 0, ceil ( $length / 2 ), $charset ) . $etc . mb_substr ( $string, - floor ( $length / 2 ), $length - ceil ( $length / 2 ), $charset );
			}
		}
	} else {
		$strlen = strlen ( $string );
		if ($strlen > $length) {
			$length -= min ( $length, strlen ( $etc ) );
			if (! $middle) {
				$string = substr ( $string, 0, floor ( $length ) ) . $etc;
			} else {
				$string = substr ( $string, 0, ceil ( $length / 2 ) ) . $etc . substr ( $string, - floor ( $length / 2 ) );
			}
		}
	}
	return $string;
}